package com.example.blogother.controller;

import com.xpd.blog.bean.Article;
import com.xpd.blog.bean.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;

@RestController
@RequestMapping("blog")
public class EmailBlogController {

    @Resource
    private JavaMailSender javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;

    @RequestMapping("sendEmailBlog")
    public Result sendSimpleMail(@RequestBody Article article, @RequestParam(value = "emailReceiver") String emailReceiver, @RequestParam int status,@RequestParam String content) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送者
        message.setFrom(from);
        // 设置邮件接收者
        message.setTo(emailReceiver);
        // 设置邮件的主题
        message.setSubject("博客审核通知");
        // 设置邮件的正文
        String text="";
        if(status==1){
            text = "你所发表的博客 '"+article.getTitle()+"' 通过了审核";
        }else{
            text = "你所发表的博客 '"+article.getTitle()+"' 中有含有"+content+"，不予通过，如多次发表该类型博客将会面临封号处理";
        }

        message.setText(text);
        // 发送邮件
        try {
            javaMailSender.send(message);
            return new Result(1,"",null);
        } catch (MailException e) {
            e.printStackTrace();
        }
        return new Result(1,"发送失败",null);
    }
}

